from flask import Flask,request,render_template,redirect,url_for,session
from forms import stealForm,registerForm,TransferForm
from exts import db
import os
from decimal import Decimal
from libs.login_requir import login_required

app=Flask(__name__)

app.secret_key=os.urandom(25)
app.config['SQLALCHEMY_DATABASE_URI']='mysql://root:mysql@127.0.0.1/test'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False

db.init_app(app)

from models import Money

@app.route('/')
def hello():
    return '<h1>welcome to 工商银行</h1><a href="/login">欢迎注册</a>'


@app.route('/login',methods=['POST','GET'])
def login():
    if request.method=='GET':
        form=stealForm()
        return render_template('login.html',form=form)
    elif request.method=='POST':
        form=stealForm(request.form)
        if form.validate():
            money=Money()
            money.password=form.password.data
            money.email=form.email.data
            money.total=form.total.data
            money.username=form.username.data
            db.session.add(money)
            db.session.commit()
            print('已经验证通过了!并且提交了数据库')
        else:
            print(form.errors)
            return redirect(url_for('login'))
        print('已经结束了！')
        return redirect(url_for('hello'))

@app.route('/register',methods=['GET','POST'])
def register():
    if request.method=='GET':
        form=registerForm()
        return render_template('register.html',form=form)
    else:
        form=registerForm(request.form)
        if form.validate():
            user=Money.query.filter(Money.email==form.email.data,Money.password==form.password.data).first()
            session['user_id']=user.id
            return '登录成功!'
        else:
            print(form.errors)
        return redirect(url_for('register'))

@app.route('/transfer',methods=['GET','POST'])
@login_required
def transfer():
    if request.method=='GET':
        form=TransferForm()
        return render_template('transfer.html',form=form)
    else:
        form=TransferForm(request.form)
        if form.validate():
            email=form.email.data
            money=form.money.data
            user_id=session.get('user_id')
            myself=Money.query.get(user_id)
            other = Money.query.filter(Money.email==email).first()
            if myself.total>=Decimal(money):
                other.total+=Decimal(money)
                myself.total-=Decimal(money)
                db.session.commit()
            else:
                print('你的转账余额不足!')
                return redirect(url_for('transfer'))
            return '恭喜你，你已经转账成功了!'


if __name__=='__main__':
    with app.app_context():
        db.drop_all()
        db.create_all()
    app.run(debug=True)